package logic

import (
	"context"
	"fmt"
	"zhihu/models"
	"zhihu/zhihu_rpc/internal/svc"
	"zhihu/zhihu_rpc/zhihu_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FindTroubleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFindTroubleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FindTroubleLogic {
	return &FindTroubleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FindTroubleLogic) FindTrouble(in *zhihu_rpc.FindTroubleRequest) (*zhihu_rpc.FindTroubleResponse, error) {
	// todo: add your logic here and delete this line
	var data struct {
		UserName string
		models.Trouble
	}
	if models.DB.Where("troubles.id = ?", in.Id).Model(&models.Trouble{}).Joins("join users on troubles.user_id = users.id").Select("troubles.*,users.user_name").Scan(&data).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if models.DB.Exec("update troubles set hot = hot + 1 where id =?", in.Id).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &zhihu_rpc.FindTroubleResponse{
		Id:        int64(data.ID),
		CreatedAt: data.CreatedAt.String(),
		UpdatedAt: data.UpdatedAt.String(),
		UserName:  data.UserName,
		Title:     data.Title,
		Des:       data.Content,
	}, nil
}
